window.onload = function() {
	var sUserAgent = navigator.userAgent;
	if (sUserAgent.indexOf('Android') > -1 || sUserAgent.indexOf('iPhone') > -1
			|| sUserAgent.indexOf('iPad') > -1
			|| sUserAgent.indexOf('iPod') > -1
			|| sUserAgent.indexOf('Symbian') > -1) {
		var ipad = document.getElementById("main");
		var wrapper = document.getElementById("wrapper");
		if(wrapper == null) return;
		
		ipad.style.width = 100 + "%";
		wrapper.style.width = 100 + "%";
		wrapper.style.left = 0;
		wrapper.style.marginLeft = 0;
	} else {
		var headCon = document.getElementById("headCon");
		headCon.style.width = 480 +"px";
	}
}
var DEBUG = false;
if (typeof window.console === "undefined"
		|| typeof window.console.log === "undefined") {
	window.console = {};
	if (DEBUG) {
		console.log = function(msg) {
			alert(msg);
		};
	} else {
		console.log = function() {
		};
	}
}

/**
 * 一些常量的定义
 */
var AccountType = {
	Seller:1,
	Buyer:2
};

/**
 * 提示全局方法
 */
function showMessage(msg){
	alert(msg);
}

/**
 * 系统配置
 */
var SystemConfig = {
	// groupshare访问服务Url
	"baseServiceUrl" : "http://www.22.com/weixinqun/rs/",
	// groupshare访问html
	"baseHtmlUrl" : "http://www.22.com/weixinqun/",
	// 文件图片等访问Url
	"imageServiceUrl" : "http://www.22.com/",
	// 登录页面
	"passport" :"http://www.22.com/weixinqun/login.html",
	// 注册页面
	"registerUrl":"http://www.22.com/weixinqun/register.html",
	// 注册URL
	getLoginUrl: function(){
		var str=window.location.href;
		return SystemConfig.passport +"?Redirect_Uri=" + escape(str);
	}
};
/**
 * 系统错误码
 */
var SystemErrorCode = {
	"Success" : "00",
	"Error" : "01",
	"UserNotLogin" : "11",
	"UnKnownError" : "X00",
	"AccessItfError" : "X01",
	"ValidateIpError" : "groupshare.filter.ValidateIpError",

	getCode : function(value) {
		for ( var p in SystemErrorCode) {
			if (value == p) {
				return SystemErrorCode[p];
			}
		}
		return value;
	}
};

 /**
  * 获得当前登录用户信息
  */
 var CurrentUser = {
 		
 	//当前登录 （#loginAccount, #uid）
 	loginUser: null,
 	/**
 	 * 初始化用户上下文信息（首页专用）
 	 */
 	initCurrent: function(){
 		$.ajax({
 	    	type: 'POST',
 	    	async: false,
 	    	contentType : "application/json; charset=UTF-8",
 	        url: SystemConfig.baseServiceUrl+'current/queryCurrentInfo',
 	        success: function (val) {
 	        	CurrentUser.loginUser = val.currentUser;
 	        }
 	    });
 	},
 	//需要登录验证
 	initCurrentUser:function(){
 		$.ajax({
 	    	type: 'POST',
 	    	async: false,
 	    	contentType : "application/json; charset=UTF-8",
 	        url: SystemConfig.baseServiceUrl + 'current/queryCurrentUserInfo',
 	        success: function (val) {
 	        	CurrentUser.loginUser = val.currentUser;
 	        }
 	    });
 	},
 	//不需要登录验证
 	initUser:function(){
 		$.ajax({
 	    	type: 'POST',
 	    	async: false,
 	    	contentType : "application/json; charset=UTF-8",
 	        url: SystemConfig.baseServiceUrl + 'current/queryUserInfo',
 	        success: function (val) {
 	        	CurrentUser.loginUser = val.currentUser;
 	        }
 	    });
 	},
 	//严格控制
 	initUserDetail:function(){
 		$.ajax({
 	    	type: 'POST',
 	    	async: false,
 	    	contentType : "application/json; charset=UTF-8",
 	        url: SystemConfig.baseServiceUrl + 'current/queryUserDetail',
 	        success: function (val) {
 	        	CurrentUser.loginUser = val.currentUser;
 	        }
 	    });
 	},
 	/**
 	 * 是否登录
 	 */
 	isLogin: function(){
 		if(CurrentUser.loginUser){
 			return true;
 		}else{
 			return false;
 		}
 	},
 	
 	/**
 	 * 当前登录用户对象
 	 */
 	getCurrentUser : function() {
 		return CurrentUser.loginUser;
 	},
 	
 	/**
 	 * 当前用户浏览器中保存的最近浏览
 	 */
 	getRecentlyViewedList : function() {
 		return CurrentUser.recentlyViewedList;
 	},
 	
 	/**
 	 * 当前登录用户的用户名
 	 */
 	getLoginAccount : function() {
 		return CurrentUser.getCurrentUser().loginAccount;
 	},
 	
 	/**
 	 * 获取用户的登录凭据
 	 */
 	getAuthkey : function() {
 		return $.cookie("_Token");
 	}
 };
/**
 * 系统工具类
 */
var SystemUtil = {
	downLoadReportIMG: function(imgPathURL) {
        //如果隐藏IFRAME不存在，则添加
//        if (!document.getElementById("IframeReportImg"))
//            $('<iframe style="display:none;" id="IframeReportImg" name="IframeReportImg" onload="SystemUtil.doSaveAsIMG();" width="0" height="0" src="about:blank"></iframe>').appendTo("body");
//        if (document.all.IframeReportImg.src != imgPathURL) {
//            //加载图片
//            document.all.IframeReportImg.src = imgPathURL;
//        }
//        else {
//            //图片直接另存为
//        	SystemUtil.doSaveAsIMG();  
//        }
        
        SystemUtil.doSaveAsIMG(imgPathURL,"qrcode_400x400.jpg"); 
    },
//    doSaveAsIMG: function() {
//        if (document.all.IframeReportImg.src != "about:blank")
//        	document.getElementById('IframeReportImg').contentWindow.document.execCommand("SaveAs");        
//    },
	doSaveAsIMG: function(fileURL, fileName) {
		    // for non-IE
		    if (!window.ActiveXObject) {
		        var save = document.createElement('a');
		        save.href = fileURL;
		        save.target = '_blank';
		        save.download = fileName || 'unknown';
		
		        var event = document.createEvent('Event');
		        event.initEvent('click', true, true);
		        save.dispatchEvent(event);
		        (window.URL || window.webkitURL).revokeObjectURL(save.href);
		    }
		
		    // for IE
		    else if ( !! window.ActiveXObject && document.execCommand)     {
		        var _window = window.open(fileURL, '_blank');
		        _window.document.close();
		        _window.document.execCommand('SaveAs', true, fileName || fileURL)
		        _window.close();
		    }
		},
    
	getKeyType : function(code) {
		if ((code <= 57 && code >= 48) || (code <= 105 && code >= 96)) {
			return 'number';
		} else if (code >= 65 && code <= 90) {
			return 'letter';
		} else if (code === 32) {
			return 'space';
		} else if (code === 110) {
			return 'point';
		} else if (code >= 112 && code <= 126) {
			return 'F1~F15'
		} else if (code >= 8 && code <= 47) {
			return 'none';
		} else {
			return 'sign';
		}
	},
	/**
	 * 日期格式化
	 * 
	 * @param {}
	 *            date 日期 可以传
	 * @param {}
	 *            format 格式化字符串 例如：yyyy-MM-dd hh:mm:ss
	 * @return {}
	 */
	format : function(date, formatString) {
		if(SystemUtil.isNull(date)){
			return null;
		}
		var time;
		if (typeof date == "number") {
			time = new Date(date);
		}
		if (date instanceof Date) {
			time = date;
		}

		var o = {
			"M+" : time.getMonth()+ 1, // month
			"d+" : time.getDate(), // day
			"h+" : time.getHours(), // hour
			"m+" : time.getMinutes(), // minute
			"s+" : time.getSeconds(), // second
			"q+" : Math.floor((time.getMonth() + 3) / 3), // quarter
			"S" : time.getMilliseconds()
		// millisecond
		}

		if (/(y+)/.test(formatString)) {
			formatString = formatString.replace(RegExp.$1,
					(time.getFullYear() + "").substr(4 - RegExp.$1.length));
		}

		for ( var k in o) {
			if (new RegExp("(" + k + ")").test(formatString)) {
				formatString = formatString.replace(RegExp.$1,
						RegExp.$1.length == 1 ? o[k] : ("00" + o[k])
								.substr(("" + o[k]).length));
			}
		}
		return formatString;
	},

	/**
	 * @author davidcun 字符类型的日期转换为Date类型, 传入的参数必须如下 2014-9-19 19:30:23
	 */
	parseDate : function(date) {
		var dt = new Date(date.replace(/-/g, "/"));
		return dt;
	},
	/**
	 * @author yindezhou 字符类型的日期转换为Date类型, 传入的参数必须如下 19:30:23/19:30
	 */
	parseTime:function(time){
		var dt=new Date();
		var t=time.split(":");
		dt.setHours(t[0]);
		
		dt.setMinutes(t[1]);
		
		if(t.length>=3){
			dt.setSeconds(t[2]);
		}else{
			dt.setSeconds("00");
		}
		return dt;
	},

	/**
	 * 生成图片url
	 * 
	 * @param oriUrl
	 *            图片原始路径
	 * @param size
	 *            生成的图片大小
	 */
	buildImageUrl : function(oriUrl, size) {
		var geneUrl = "";
		if (SystemUtil.isNull(oriUrl)) {
			return geneUrl;
		}
		if(oriUrl.charAt(0)==='\\' || oriUrl.charAt(0)==='/'){
			oriUrl=oriUrl.substr(1);
		}
		var pointLocation = oriUrl.lastIndexOf("."),
			filePath = oriUrl.substring(0,pointLocation),
			fileType = "_"+size+oriUrl.substring(pointLocation);
		geneUrl = SystemConfig.imageServiceUrl+filePath + fileType
		return geneUrl;
	},
	/**
	 * 短信按钮定时，重发方法实现
	 * @param mobileMessage 按钮对象
	 * @param countTime   定时时间
	 */
	sendSMSCountDown : function(mobileMessage, countTime) {
		if (countTime == 0) {
			mobileMessage.attr("disabled", false);
			mobileMessage.val(mobileMessage.val().substr(0,
					mobileMessage.val().length - 3));
		} else {
			mobileMessage.attr("disabled", true);
			mobileMessage.val(mobileMessage.val().replace(
					'(' + (countTime + 1) + ')', '')
					+ '(' + countTime + ')');
			var timeout = setTimeout(function() {
				clearTimeout(timeout);
				SystemUtil.sendSMSCountDown(mobileMessage, --countTime);
			}, 1000);
		}
	},
	// 获取URL对应参数值
	getUrlParam : function(name) {
		return SystemUtil.getUrlParamByUrl(window.location.search, name);
	},
	getUrlParamByUrl:function(urlSearch,name){
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
		var r = urlSearch.substr(1).match(reg); // 匹配目标参数
		if (r != null){
			return decodeURIComponent(r[2]);
		}
		return null; // 返回参数值
	},
	// 判断是否为空
	isNull : function(value) {
		var type = jQuery.type(value);
		if (type === "undefined" || type === "" || type === "null"
				|| value === "null" || value === null || value === ""
				|| value === "undefined") {
			return true;
		} else {
			return false;
		}
	},
	// 保留两位小数
	// 功能：将浮点数四舍五入，取小数点后2位
	toDecimal : function(x) {
		var f = parseFloat(x);
		if (isNaN(f)) {
			return;
		}
		f = Math.round(x * 100) / 100;
		return f;
	},
	// 强制保留2位小数，如：2，会在2后面补上00.即2.00
	toDecimal2 : function(x) {
		var f = parseFloat(x);
		if (isNaN(f)) {
			return false;
		}
		var f = Math.round(x * 100) / 100;
		var s = f.toString();
		var rs = s.indexOf('.');
		if (rs < 0) {
			rs = s.length;
			s += '.';
		}
		while (s.length <= rs + 2) {
			s += '0';
		}
		return s;
	},
	menuRequest : function(url) {
		window.location.href = SystemConfig.baseHtmlUrl + url;
	},
	openNewTabRequest:function(url){
		window.open(SystemConfig.baseHtmlUrl + url);
	},
	// UUID,len是生成UUID的长度
	uuid : function(len, radix) {
		var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
				.split('');
		var uuid = [], i;
		radix = radix || chars.length;
		if (len) {
			for (i = 0; i < len; i++)
				uuid[i] = chars[0 | Math.random() * radix];
		} else {
			var r;
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
			uuid[14] = '4';
			for (i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | Math.random() * 16;
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
				}
			}
		}
		return uuid.join('');
	},
	//时钟
	clock : {
		nowTime : null,
		obj : null,
		start : function(date, id, text) {
			this.stop();
			this.nowTime = date;
			this.obj = setInterval('SystemUtil.clock.go(\'' + id + '\',\'' + text + '\')', 1000);
		},
		go : function(id, html) {
			var date = SystemUtil.format(this.nowTime, 'yyyy-MM-dd hh:mm:ss');
			$('#' + id).text(date + html);
			this.nowTime += 1000;
		},
		stop : function() {
			clearInterval(this.obj);
		}
	}
};


/**
 * 表单验证类
 * */
var Validation={
	isNotEmpty:function(v){
		if(v==""||v==null){
			return false;
		}else{
			return true;
		}
	},
	//是否是邮箱
	isEmail:function(v){
		var filter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if(!filter.test(v)){

			return false;
		} else {
			return true;
		}
	},
	// 是否是数字
	isNum : function(v) {
		return !isNaN(v) ? true : false;
	},
	// 手机号码验证
	isMobileNum : function(v) {
		var filter = /^1[3|5|7|8|][0-9]{9}$/;
		return filter.test(v);
	},
	//固定电话验证
	isTelPhone:function(v){
		var filter=/^0([3-9][0-9]{1,2}|[1-2]\d)[1-9][0-9]{6,7}$/;
		return filter.test(v);
	},
	//验证时间格式 是否满足 00:00
	isTimeMS:function(v){
	    var filter=/^(([1-9]{1})|([0-1][0-9])|([1-2][0-3])):([0-5][0-9])$/;
	    return filter.test(v);
	},
	//验证时间格式 是否满足 00:00:00
	isTime:function(v){
		var filter=/^(([1-9]{1})|([0-1][0-9])|([1-2][0-3])):([0-5][0-9]):([0~5][0~9])+$/;
    	if(!filter.test(v)){
    		return false;
    	}else{
    		return true;
    	}
	},
	
	//验证日期格式  2014-05-19 23:59:59
	isDateAndTime:function(v){
		var filter=/^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))\s(([1-9]{1})|([0-1][0-9])|([1-2][0-3])):([0-5][0-9]):([0~5][0~9])+$/;
		if(filter.test(v)){

			return true;
		}
		return false;
	},
	// 验证日期格式2014-05-19
	isDate : function(v) {
		var filter = /^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))+$/;
	},
	// 验证正整数
	isIntNum : function(v) {
		var filter = /^[1-9][0-9]*$/;
		if (filter.test(v)) {
			return true;
		}
		return false;
	},
	//验证是否为Excel文件
	isExcelFile:function(v){
		var fileName = /^.*\.(xlsx|xls)$/i;
		return fileName.test(v);
	},
	isQQNum:function(v){
		var filter=/[1-9][0-9]{4,}$/;
		return filter.test(v);
	},
	isChinese:function(v){
		var filter= /[\u4e00-\u9fa5]$/;
		return filter.test(v);
	},
	isImageFile: function(filepath){
		var extStart=filepath.lastIndexOf(".");
		var ext=filepath.substring(extStart,filepath.length).toUpperCase();
		if(ext!=".BMP"&&ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"){
			return false;
		}else{
			return true;
		}
	}
};

/**
 * 扩展Jquery
 */
(function($) {
	// 备份jquery的ajax方法
	var _ajax = $.ajax;
	// 重写jquery的ajax方法
	$.ajax = function(opt) {
		// 备份opt中error和success方法
		var fn = {
			error : function(XMLHttpRequest, textStatus, errorThrown) {
			},
			exception : function(data, textStatus, XMLHttpRequest) {
			},
			unknownexception : function(data, textStatus, XMLHttpRequest) {
			},
			success : function(data, textStatus, XMLHttpRequest) {
			},
			handelResponse : function(data, textStatus, XMLHttpRequest) {
				var contentType = XMLHttpRequest.getResponseHeader('Content-Type');
				if (contentType&&contentType.toLowerCase().indexOf('application/json') > -1) {
					if (data) {
						// 业务执行成功
						if (data.success && !data.isException) {
							fn.success(data, textStatus, XMLHttpRequest);
							// 业务异常
						} else if (!data.success && !data.isException) {
							fn.exception(data, textStatus, XMLHttpRequest);
							// 未知异常
						} else if (!data.success && data.isException) {
							// 如果是用户未登录，跳转到登录页面
							if (SystemErrorCode.UserNotLogin == data.responseStatus.code) {
								window.location.href = SystemConfig.getLoginUrl();
								//抛出未登录异常，终止执行以后的代码
								throw "用户未登录，跳转登录页面"; 
							}else if(SystemErrorCode.ValidateIpError == data.responseStatus.code){
								window.location.href = SystemConfig.baseHtmlUrl + 'error.html';
								//抛出IP白名单验证异常，终止执行以后的代码
								throw "IP白名单验证异常"; 
							}else {
								if (fn.unknownexception) {
									fn.unknownexception(data, textStatus,
											XMLHttpRequest);
								} else {
									// TODO 增加通用的信息提示
									alert(data.responseStatus.message);
								}								
							}
						}
					}
				} else {
					if (XMLHttpRequest.responseJSON) {
						if (XMLHttpRequest.responseText
								.indexOf('<meta content="LOGIN_JSP"/>') > 0) {
							window.location.href = SystemConfig.getLoginUrl();
							return;
						}
					}
					fn.success(data, textStatus, XMLHttpRequest);
				}
			}
		}
		if (opt.error) {
			fn.error = opt.error;
		}
		if (opt.exception) {
			fn.exception = opt.exception;
		}
		if (opt.unknownexception) {
			fn.unknownexception = opt.unknownexception;
		}
		if (opt.success) {
			fn.success = opt.success;
		}

		// 扩展增强处理
		var _opt = $.extend(opt, {
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				fn.error(XMLHttpRequest, textStatus, errorThrown);
			},
			success : function(data, textStatus, XMLHttpRequest) {
				var me = this;
				// 请求成功的处理
				fn.handelResponse(data, textStatus, XMLHttpRequest);
			}
		});
		return _ajax(_opt);
	};
	/**
	 * 业务字典信息类
	 */
	$.dataDictionary = {
	    /**
	     * 通过类型请求服务端加载字典数据
	     * @param dictType
	     */
	    loadDictDataByType: function(dictType) {
	        Ext.Ajax.request({
	            url: './rs/dictionary/loadDictionaryByType',
	            method: 'POST',
	            jsonData: {
	                type: dictType
	            },
	            async: false,
	            success: function(response){
	                var josn = Ext.decode(response.responseText),
	                    dictionaryjson = josn.jsonData,dictionaryList;
	                if(Ext.isEmpty(dictionaryjson)) {
	                    dictionaryjson = "[]";
	                }
	                dictionaryList = Ext.decode(dictionaryjson);
	                dataDictionary.add(dictType, dictionaryList);
	            }
	        });
	    },
	    /**
	     * 通过类型加载字典数据
	     * @param dictType
	     * @returns {*}
	     */
	    getDictDataByType: function(dictType) {
	        if(Ext.isEmpty(dictType)) {
	            return;
	        }
	        var dictData = dataDictionary.get(dictType);
	        if(Ext.isEmpty(dictData)) {
	            DataDictionary.loadDictDataByType(dictType);
	            dictData = dataDictionary.get(dictType);
	        }
	        return Ext.clone(dictData);
	    },
		/**
		 * 将业务字典的displayValue（数据字典显示值）转换成描述submitValue（提交值）
		 * 使用方法rendererDictionary(displayValue,’abc’);
		 * 
		 * @param value
		 *            所要转换的值
		 * @param termsCode
		 *            词条代码
		 */
		rendererDisplayToSubmit : function(displayValue, termsCode) {
			var data = $.dataDictionary[termsCode];
			if (!SystemUtil.isNull(displayValue) && !SystemUtil.isNull(data)) {
				for ( var i = 0; i < data.length; i++) {
					if (displayValue == data[i].display) {
						return data[i].value;
					}
				}
			}
			return displayValue;
		},
		/**
		 * 将业务字典的submitValue（提交值）转换成描述displayValue（数据字典显示值）
		 * 使用方法rendererDictionary(value,’abc’);
		 * 
		 * @param value
		 *            所要转换的值
		 * @param termsCode
		 *            词条代码
		 */
		rendererSubmitToDisplay : function(submitValue, termsCode) {
			var data = $.dataDictionary[termsCode];
			if (!SystemUtil.isNull(submitValue) && !SystemUtil.isNull(data)) {
				for ( var i = 0; i < data.length; i++) {
					if (submitValue == data[i].value) {
						return data[i].display;
					}
				}
			}
			return submitValue;
		},
		/**
		 * 数据字典选择器
		 * 
		 * @param selectId
		 *            选择器ID
		 * @param termsCode
		 *            词条代码
		 */
		createDataDictionary : function(selectId, termsCode) {
			$('#' + selectId).empty();
			var dictionaryData = $.dataDictionary[termsCode];
			$.singleSelector({
				'value' : 'value',// 提交值对应的key
				'display' : 'display',// 显示值对应的key
				'selectId' : selectId, // 选择器的select Id
				'selectValue' : dictionaryData
			// 选择器数据
			});
		}
	};
	window.inputNum=function(options){
		var settings = $.extend({
			minValue:null,
			maxValue:null,
			defaultValue:0,
			itemId:'',
			itemName:'',
			itemClass:''
		}, options);
		
		var $obj=$('<input type="text" name="'+settings.itemName+'" class="'+settings.itemClass+'"/> id="'+settings.itemId+'"');
		$obj.appendTpo("body");
	}
    $.fn.inputNum=function(options){
    	var settings = $.extend({
			minValue:null,
			maxValue:null,
			defaultValue:0
		}, options);
    	var verfiy=function(){
    		if(isNaN(settings.minValue) || isNaN(settings.maxValue) || isNaN(settings.defaultValue)){
    			return;
    		}
    	}
    	$(this).live('blur',function(){
    		verfiy();
    		var value=$(this).val();
    		if(SystemUtil.isNull(value) || isNaN(value)){
    				$(this).val(settings.defaultValue);
    		}else{
    			if(Number(value)!=Number(settings.defaultValue)){
    				if(Number(value)>settings.maxValue){
        				$(this).val(settings.maxValue);
        			}
        			if(Number(value)<settings.minValue){
        				$(this).val(settings.minValue);
        			}
    			}
    		}
    	});
    	$(this).live('keyup',function(){
    		verfiy();
    		var v=$(this).val();
    		if(isNaN(v)){
    			$(this).val("");
    		}
    	});
    }
	/**
	 * 单选框
	 */
	$.singleSelector = function(options) {
		// 默认参数
		var settings = $.extend({
			'dataInit' : true,// 是否初始化数据,默认为true
			'root' : 'root',// 返回数据的根名称
			'emptyText' : '请先选择',// 未选择时的显示
			'value' : 'value',// 提交值对应的key
			'display' : 'display',// 显示值对应的key
			'selectId' : 'selectId', // 选择器的select Id
			'selectValue' : [], // 默认的选择器数据
			'params' : {}, // 配置的请求参数
			'contentType' : "application/json; charset=UTF-8",// 数据请求的contentType
			'dataType' : "json",// 服务器返回的数据类型
			'parentParam' : null, // 级联选择的父选择器的id与提交值对应的key
			'url' : '' // 得到数据的url
		}, options);

		// 选择器对象
		var $selectObj = $("#" + settings.selectId),

		/**
		 * Private Methods : _setSelectValue
		 * 
		 * 将json填充到指定select组件上
		 * 
		 * @param jsonVal :
		 *            json对象，要填充到select组件上的json对象
		 * @param $selectObj :
		 *            要填充的select组件
		 * @private
		 */
		_setSelectValue = function(jsonVal, $selectObj) {
			$.each(jsonVal, function(index, object) {
				_appendOptionTo($selectObj, object[settings.display],
						object[settings.value]);
			});
		},

		/**
		 * Private Methods : _appendOptionTo
		 * 
		 * 将值增加到option组件
		 * 
		 * @param $selectObj :
		 *            The selected object jquery，一般为需要添加option的select对象
		 * @param key :
		 *            option的key，一般为设置的Id
		 * @param val ;
		 *            option的val，同时一般也作为显示的值，在这里我们默认为显示的value和option的value是同一个值
		 * @param defaultSelectVal ;
		 *            设置默认选中的值，一般为初始化的情况下，默认选中的value
		 * @private
		 */
		_appendOptionTo = function($selectObj, key, val, defaultSelectVal) {
			var $opt = $("<option>").text(key).val(val);
			if (val == defaultSelectVal) {
				$opt.attr("selected", "selected");
			}
			$opt.appendTo($selectObj);
		},

		/**
		 * Public Methods : _dataLoad
		 * 
		 * 当select组件的value发生改变时，对下一级select组件value产生的影响，即下一级select组件值的改变
		 * 
		 * @param isLink :
		 *            判断是否级联选择器，如果是级联选择器，那么不管选择器中是否已经有值都要进行重新load数据
		 */
		_dataLoad = function(isLink) {
			// 如果数据中的selectValue不为空，那么直接拿数据进行显示，如果为空通过请求获得数据在进行显示。
			if (isLink || settings.selectValue.length == 0) {
				var queryParams = settings.params, parentParam = settings.parentParam;
				if (parentParam != null) {
					$.each(parentParam, function(parentId, queryParam) {
						queryParams[queryParam] = $("#" + parentId).val();
					});
				}
				// ajax异步获取菜单数据
				$.ajax({
					type : 'POST',
					url : settings.url,
					contentType : settings.contentType,
					dataType : settings.dataType,
					data : queryParams,
					success : function(val) {
						settings.selectValue = val[settings.root];
						_setSelectValue(settings.selectValue, $selectObj);
					}
				});
			} else {
				_setSelectValue(settings.selectValue, $selectObj);
			}
		};

		// 未选择时的显示条目
		$("<option value=''>" + settings.emptyText + "</option>").appendTo(
				$selectObj);

		// 是否数据初始化
		if (settings.dataInit === true) {
			_dataLoad();
		}

		// 返回选择方法
		return _dataLoad;
	};

	$.linkageSelector = function(options) {
		var i = 0, indexs = [], selectorSettions = {}, dataLoads = {}, selectors = {};

		$.each(options, function(selectId, selectOptions) {
			var settings = $.extend({
				'selectId' : selectId
			// 选择器Id
			}, selectOptions);
			indexs[i++] = selectId;
			selectorSettions[selectId] = settings;
			selectors[selectId] = $("#" + selectId);
			dataLoads[selectId] = $.singleSelector(settings);
		});

		for ( var i = indexs.length - 2; i >= 0; i--) {
			selectors[indexs[i]].change(function(event) {
				var index = -1;
				$.each(indexs, function(j, selectId) {
					if (selectId === event.target.id) {
						index = j + 1;
					}
				});
				_changeMenu(selectors[event.target.id],
						selectors[indexs[index]], index, true);
			});
		}

		/**
		 * Private Methods : _changeMenu
		 * 
		 * 当select组件的value发生改变时，对下一级select组件value产生的影响，即下一级select组件值的改变
		 * 
		 * @private
		 */
		function _changeMenu(preSelectIdObj, folSelectIdObj, index, isFirst) {
			if (index >= indexs.length) {
				return;
			}
			var folSelectId = folSelectIdObj.attr("id");
			folSelectIdObj.html("");
			var selector = selectorSettions[folSelectId];
			selector["selectValue"] = [];				
			$(
					"<option value=''>"
							+ selectorSettions[folSelectId].emptyText
							+ "</option>").appendTo(folSelectIdObj);
			if (isFirst) {
				dataLoads[folSelectId](true);
			}
			_changeMenu(selectors[indexs[index]], selectors[indexs[index + 1]],
					index + 1, false);
		}
	};

	/**
	 * 分页 maxentries 总数 opts 分页参数
	 */
	$.fn.pagination = function(maxentries, opts) {
		opts = jQuery.extend({
			method_type : 'POST',
			url : '',
			items_per_page : 10,
			num_display_entries : 5,
			current_page : 0,
			num_edge_entries : 1,
			link_to : "#",
			prev_text : "<上一页",
			next_text : "下一页>",
			ellipse_text : "...",
			prev_show_always : true,
			next_show_always : true,
			input_able : true,
			totalCount : maxentries,
			defaultValue : null,
			callParams : function() {
				return {}
			},
			callback : function() {
			}
		}, opts || {});

		return this
				.each(function() {
					/**
					 * Calculate the maximum number of pages
					 */
					function numPages() {
						return Math.ceil(opts.totalCount / opts.items_per_page);
					}

					/**
					 * Calculate start and end point of pagination links
					 * depending on current_page and num_display_entries.
					 * 
					 * @return {Array}
					 */
					function getInterval() {
						var ne_half = Math.ceil(opts.num_display_entries / 2);
						var np = numPages();
						var upper_limit = np - opts.num_display_entries;
						var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
						var end = current_page > ne_half ? Math.min(current_page + ne_half, np) : Math.min(opts.num_display_entries, np);
						return [ start, end ];
					}

					/**
					 * This is the event handling function for the pagination
					 * links.
					 * 
					 * @param {int}
					 *            page_id The new page number
					 */
					function pageSelected(page_id, evt) {
						current_page = page_id;
						drawLinks();
						var continuePropagation = handelReslut(page_id * opts.items_per_page);
						if (!continuePropagation) {
							if (evt.stopPropagation) {
								evt.stopPropagation();
							} else {
								evt.cancelBubble = true;
							}
						}
						return continuePropagation;
					}

					function handelReslut(current_page) {
						var queryParams = {
							limit : opts.items_per_page,
							start : current_page
						}, otherParams = opts.callParams();
						jQuery.extend(queryParams, otherParams);
						if (SystemUtil.isNull(opts.defaultValue)) {
							$.ajax({
								type : opts.method_type,
								url : opts.url,
								contentType : "application/json; charset=UTF-8",
								dataType : 'json',
								data : $.toJSON(queryParams),
								success : function(resp) {
									opts.totalCount = resp.totalCount;
									opts.callback(resp, this);
									drawLinks();
								}
							});
						} else {
							opts.totalCount = opts.defaultValue.length;
							opts.callback(opts.defaultValue, this);
							drawLinks();
						}
						return true;
					}

					/**
					 * This function inserts the pagination links into the
					 * container element
					 */
					function drawLinks() {
						panel.empty();
						if (opts.totalCount === 0) {
							return;
						}
						var interval = getInterval();
						var np = numPages();
						// This helper function returns a handler function that
						// calls pageSelected with the right page_id
						var getClickHandler = function(page_id) {
							return function(evt) {
								return pageSelected(page_id, evt);
							}
						}
						// Helper function for generating a single link (or a
						// span tag if it's the current page)
						var appendItem = function(page_id, appendopts) {
							page_id = page_id < 0 ? 0 : (page_id < np ? page_id : np - 1); // Normalize page id to sane
							// value
							appendopts = jQuery.extend({
								text : page_id + 1,
								classes : ""
							}, appendopts || {});
							if (page_id == current_page) {
								var lnk = jQuery("<span class='current'>" + (appendopts.text) + "</span>");
							} else {
								var lnk = jQuery("<a>" + (appendopts.text) + "</a>")
										.bind("click", getClickHandler(page_id));
//										.attr('href',opts.link_to.replace(/__id__/,page_id));
							}
							if (appendopts.classes) {
								lnk.addClass(appendopts.classes);
							}
							panel.append(lnk);
						}
						// Generate "Previous"-Link
						if (opts.prev_text && (current_page > 0 || opts.prev_show_always)) {
							appendItem(current_page - 1, {
								text : opts.prev_text,
								classes : "prev"
							});
						}
						// Generate starting points
						if (interval[0] > 0 && opts.num_edge_entries > 0) {
							var end = Math.min(opts.num_edge_entries,interval[0]);
							for ( var i = 0; i < end; i++) {
								appendItem(i);
							}
							if (opts.num_edge_entries < interval[0] && opts.ellipse_text) {
								jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
							}
						}
						// Generate interval links
						for ( var i = interval[0]; i < interval[1]; i++) {
							appendItem(i);
						}
						// Generate ending points
						if (interval[1] < np && opts.num_edge_entries > 0) {
							if (np - opts.num_edge_entries > interval[1] && opts.ellipse_text) {
								jQuery("<span>" + opts.ellipse_text + "</span>").appendTo(panel);
							}
							var begin = Math.max(np - opts.num_edge_entries, interval[1]);
							for ( var i = begin; i < np; i++) {
								appendItem(i);
							}

						}
						// Generate "Next"-Link
						if (opts.next_text && (current_page < np - 1 || opts.next_show_always)) {
							appendItem(current_page + 1, {
								text : opts.next_text,
								classes : "next"
							});
						}

						// 扩展添加 手动输入页数跳转
						if (opts.input_able) {
							jQuery("<span class='pagenation_span'>跳转到</span>"
									+ "<input class='input_number' type='number'  min='1' max='"
									+ np + "' id='page_numer'/>").appendTo(panel);
							jQuery('<input type="button" value = "确定" class="page_number_sure" />')
									.bind('click',function() {
										current_page = $('#page_numer').val() - 1;
										handelReslut(current_page * opts.items_per_page);
										drawLinks();
									}).appendTo(panel);
							$('#page_numer').val(current_page + 1);
							$('#page_numer').keydown(function(e){
								var keyType=SystemUtil.getKeyType(e.keyCode);
								if(keyType!='number' && keyType!='F1~F15' && keyType!='none'){
									e.preventDefault();
								}
							});
							$('#page_numer').keyup(function(){
								var value = ($(this).val() > np) ? np : $(this).val();
								value = (value == '') ? 0 : value;
								value = (value < 1) ? 1 : value;
								$(this).val(value);
							});
						}
					}

					// Extract current_page from options
					var current_page = opts.current_page;
					// Create a sane value for opts.totalCount and
					// items_per_page
					opts.totalCount = (!opts.totalCount || opts.totalCount < 0) ? 1
							: opts.totalCount;
					opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0) ? 1
							: opts.items_per_page;
					// Store DOM element for easy access from all inner
					// functions
					var panel = jQuery(this);
					// Attach control functions to the DOM element
					this.selectPage = function(page_id) {
						pageSelected(page_id);
					}
					this.selectCurrentPage = function() {
						pageSelected(current_page);
					}
					this.prevPage = function() {
						if (current_page > 0) {
							pageSelected(current_page - 1);
							return true;
						} else {
							return false;
						}
					}
					this.nextPage = function() {
						if (current_page < numPages() - 1) {
							pageSelected(current_page + 1);
							return true;
						} else {
							return false;
						}
					}
					// call callback function
					handelReslut(current_page);
					// When all initialisation is done, draw the links
					drawLinks();

				});

	};
	
	/**
	 * @author yindezhou
	 * 模态弹窗封装
	 * */
	$.fn.modalDialog=function(options){
	    var defaults={
	    		top:100,           //距离浏览器顶部距离
	    		overlay:0.3,       //遮罩层颜色深度 即非透明度
	    		closeButton:null,  //关闭按钮
	    		$modal_id:null,    //要显示的窗口元素id（一般div）
	    		isClose:true,      //点击遮罩层是否关闭遮罩，默认为关闭
	    		submitButton:null, //提交按钮
	    		beforeSubmit:function(){},
	    		submitUrl:'',      //提交ActionUrl
	    		submitData:{},     //提交参数
	    		submitSuccess:function(){},  //提交成功 回调
	    		submitException:function(){},//异常回调
	    		submitDataType : 'json',     //参数数据类型
	    		submitType:'POST',           //提交方式
	    		winHeight:'404',             //窗口高度 默认404
	    		winWidth:'404'               //窗口宽度 默认404
	    	};
	    options=$.extend(defaults,options);
	    var overlay=$('<div id="lean_overlay"></div>');
	    $(this).append(overlay);
	    var $modal_id=options.$modal_id;
        $(options.closeButton).click(function(){
            close_modal($modal_id);
        });
        $("#"+$modal_id).children('.pupup_title').children('.close').click(function(){
        	close_modal($modal_id);
        });
        var modal_height=$("#"+$modal_id).outerHeight();
        var modal_width=$("#"+$modal_id).outerWidth();
       
        overlay.css({"display":"block",opacity:0});
	    overlay.fadeTo(200,options.overlay);
	    var winHeight=$(this).outerHeight();
	    var topHeight=($(this).outerHeight()-options.winHeight)/2;
        if($(this)===$("body")){
        	topHeight=(window.height()-options.winHeight)/2;
        }
	    $("#"+$modal_id).css({
	    	"display":"block",
	    	"position":"fixed",
	    	"opacity":0,
	    	"z-index":11000,
	    	"left":50+"%",
	    	"margin-left":-(modal_width/2)+"px",
	    	"min-height":options.winHeight+"px",
	    	"width":options.winWidth});
	    $("#"+$modal_id).fadeTo(200,1);
	    if(!SystemUtil.isNull(options.submitButton)){
        	$(options.submitButton).click(function(){
        		if(options.beforeSubmit()){
        			$.ajax({
            			type : options.submitType,
            			contentType : 'application/json; charset=UTF-8',
            			url : options.submitUrl,
            			dataType : options.submitDataType,
            			data : $.toJSON(options.submitData),
            			success : function(resp){
            				close_modal($modal_id);
            				options.submitSuccess(resp);
            			},
            			exception: function(resp){
            				close_modal($modal_id);
            				options.submitException(resp);
            				return;
            			}
            			
            		});
        		}
        		
            });
        }
	   function close_modal($modal_id){
		    overlay.remove();
		    $(options.submitButton).unbind( "click" );
		    $("#"+$modal_id).css({"display":"none"});
	   }
    }
	$.fn.modelHanding=function(overDelay){
		 var html='<div class="over_img_info" id="handling_info"></div>';
		 var options;
		 $(this).append(html);
		 options={
		       	   top: 200,
			       $modal_id:"handling_info",
			       winHeight:"60",
			       winWidth:"180",
			       isClose:false
			 };
		if(!overDelay){
			options.overlay=0;
		 }
		$(this).modalDialog(options);
	}
	
	$.closeHanding=function close_handing(){
		 $("#handling_info").remove();
		 $("#lean_overlay").remove()
	 }
	
	$.exchangeBtn=function(options){
		 var defaults={
		     btnId:null,//a标签按钮id
		     ableClass:"a_btn_blue",//按钮可点时的样式 class  默认值a_btn_blue
		     grayClass:"a_btn_gray",//按钮灰色时样式 class   默认值a_btn_gray
		     emText:"获取验证码",//按钮文本
		     grayText:"",//按钮灰色显示文本 默认空值
		     clickFun:function(){},//按钮点击事件
		     countTimeScd:30,//计时时常,默认30秒
		     timeBegin:false //按钮刚开始是否计时
		 };
		 options=$.extend(defaults,options);
		 var messageEm=$("#"+options.btnId).children()[0];
		 messageEm.innerText=options.emText;//初始化按钮文本
		 var SmsCountTimeDown=function(mobileMessage, countTime) {
			if (countTime == 0) {
				mobileMessage.removeClass(options.grayClass).addClass(options.ableClass);
				messageEm.innerHTML=options.emText;
					/*messageEm.innerText.substr(0,
						messageEm.innerHTML.length - 4);*/
				mobileMessage.bind("click",function(){
					SmsCountTimeDown(mobileMessage,options.countTimeScd);
					options.clickFun();
				});
			} else {
				mobileMessage.removeClass(options.ableClass).addClass(options.grayClass);
				mobileMessage.unbind("click");
				var msgText=SystemUtil.isNull(options.grayText)?messageEm.innerHTML:options.grayText;
				var time=countTime<10?"0"+countTime:countTime;
				var timePlusOne=countTime<9?"0"+(countTime+1):countTime+1;

				messageEm.innerHTML=msgText.replace(
						'(' + timePlusOne + ')', '')
						+ '(' + time + ')';
				var timeout = setTimeout(function() {
					clearTimeout(timeout);
					SmsCountTimeDown(mobileMessage, --countTime);
				}, 1000);
			}
		}
		if(options.timeBegin){
			SmsCountTimeDown($("#"+options.btnId),options.countTimeScd);
			return;
		}
		$("#"+options.btnId).click(function(){
			SmsCountTimeDown($(this),options.countTimeScd);
			options.clickFun();
		});
	}
})(jQuery);
